package com.jl.encrypt;

import com.jl.encrypt.annotate.Decode;
import com.jl.encrypt.config.SecretKeyConfig;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.lang.reflect.Type;

/**
 * body入参拦截
 */
@Slf4j
@ControllerAdvice
@ConditionalOnExpression("${security.encrypt.open:false}")
public class JRequestBodyAdvice implements RequestBodyAdvice {

    @Autowired
    private SecretKeyConfig secretKeyConfig;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.getMethod().isAnnotationPresent(Decode.class) && secretKeyConfig.getOpen() ? true : false;
    }

    @Override
    @SneakyThrows
    public org.springframework.http.HttpInputMessage beforeBodyRead(org.springframework.http.HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                                                    Class<? extends HttpMessageConverter<?>> converterType) {
        if (parameter.getMethod().isAnnotationPresent(Decode.class)) {
            return new JHttpInputMessage(inputMessage, secretKeyConfig.getAes(), secretKeyConfig.getRsa(), secretKeyConfig.getShowLog());
        }
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, org.springframework.http.HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, org.springframework.http.HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
